package com.mdnote.practice.binary_search;

/**
 * @author Rhythm-2019
 * @version 1.0
 * @date 2020/9/18
 * @description 寻找旋转排序数组中的最小值
 */
public class LeetCode153 {

    public static void main(String[] args) {
        LeetCode153 leetCode153 = new LeetCode153();
        int res = leetCode153.findMin(new int[]{4, 5, 1, 2, 3});
        System.out.println(res);
    }

    public int findMin(int[] nums) {

        if (nums.length == 0) {
            return -1;
        }
        if (nums.length == 1) {
            return nums[0];
        }
        if (nums[0] < nums[nums.length - 1]) {
            return nums[0];
        }

        return nums[binarySearch(nums)];
    }

    private int binarySearch(int[] nums) {

        int left = 0;
        int right = nums.length - 1;

        while (left <= right) {
            int mid = (right - left) / 2 + left;
            if (nums[mid] > nums[mid + 1]) {
                return mid + 1;
            }
            if (nums[mid - 1] > nums[mid]) {
                return mid;
            }
            // 判断左边是不是有序的
            if (nums[left] < nums[mid]) {
                // 左边是有序的，对右边进行二分查找
                left = mid + 1;

            } else {
                // 右边是有序的，对左边进行二分查找
                right = mid - 1;
            }
        }
        return left;
    }


}
